<template>
  <div class="attraction-detail-container">
    <div class="navigation-buttons">
      <el-button type="primary" plain @click="goHome">
        <el-icon><Back /></el-icon>
        返回首页
      </el-button>
      <el-button plain @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
        返回上一页
      </el-button>
    </div>
    
    <el-card class="attraction-card" v-loading="loading">
      <div v-if="attraction">
        <div class="attraction-header">
          <h1>{{ attraction.name }}</h1>
          <div class="attraction-meta-top">
            <el-tag size="small">{{ attraction.category?.categoryName }}</el-tag>
            <div class="rating">
              <el-rate
                v-model="attraction.avgRating"
                disabled
                text-color="#ff9900"
                :max="5"
              />
              <span>{{ attraction.avgRating }} 分</span>
            </div>
            <span class="view-count">
              <el-icon><View /></el-icon>
              {{ attraction.viewCount }} 浏览
            </span>
          </div>
        </div>
        
        <div class="attraction-content">
          <div class="attraction-gallery">
            <el-carousel :interval="4000" type="card" height="400px" v-if="attraction.coverImages && attraction.coverImages.length > 0">
              <el-carousel-item v-for="(image, index) in attraction.coverImages" :key="index">
                <img :src="image" :alt="`${attraction.name} - 图片 ${index + 1}`" class="carousel-image" />
              </el-carousel-item>
            </el-carousel>
            <img v-else src="../assets/placeholder.jpg" class="attraction-image" />
          </div>
          
          <div class="attraction-info">
            <div class="attraction-description">
              <h2>景点简介</h2>
              <p>{{ attraction.description }}</p>
            </div>
            
            <div class="attraction-meta">
              <div class="meta-item">
                <el-icon><Location /></el-icon>
                <span>{{ attraction.address }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Ticket /></el-icon>
                <span>门票: ¥{{ attraction.ticketPrice }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Clock /></el-icon>
                <span>开放时间: {{ formatOpeningHours(attraction.openingHours) }}</span>
              </div>
              <div class="meta-item" v-if="attraction.contactPhone">
                <el-icon><Phone /></el-icon>
                <span>联系电话: {{ attraction.contactPhone }}</span>
              </div>
              <div class="meta-item" v-if="attraction.website">
                <el-icon><Link /></el-icon>
                <a :href="attraction.website" target="_blank" rel="noopener noreferrer">官方网站</a>
              </div>
            </div>
            
            <div class="attraction-tags" v-if="attraction.tags && attraction.tags.length > 0">
              <el-tag
                v-for="tag in attraction.tags"
                :key="tag"
                class="tag-item"
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
            
            <div class="attraction-actions">
              <el-button type="primary" @click="addToFavorites">
                <el-icon><Star /></el-icon>
                收藏景点
              </el-button>
              <el-button type="success" @click="viewOnMap">
                <el-icon><MapLocation /></el-icon>
                查看地图
              </el-button>
            </div>
          </div>
        </div>
        
        <div class="attraction-detail-section" v-if="attraction.detail">
          <h2>详细介绍</h2>
          <div class="detail-content">{{ attraction.detail }}</div>
        </div>
        
        <div class="attraction-traffic-section" v-if="attraction.trafficGuide">
          <h2>交通指南</h2>
          <div class="traffic-content">{{ attraction.trafficGuide }}</div>
        </div>
        
        <div class="attraction-gallery-section" v-if="attraction.imageGallery && attraction.imageGallery.length > 0">
          <h2>景点图集</h2>
          <div class="gallery-container">
            <el-image
              v-for="(image, index) in attraction.imageGallery"
              :key="index"
              :src="image"
              :preview-src-list="attraction.imageGallery"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="0"
              fit="cover"
              class="gallery-image"
            />
          </div>
        </div>
        
        <div class="attraction-comments-section">
          <h2>用户评论</h2>
          
          <div class="comment-form-container" v-if="isLoggedIn">
            <el-form :model="commentForm" ref="commentFormRef" :rules="commentRules">
              <el-form-item prop="content">
                <el-input
                  v-model="commentForm.content"
                  type="textarea"
                  :rows="3"
                  placeholder="分享您对这个景点的看法..."
                  maxlength="500"
                  show-word-limit
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitComment" :loading="submittingComment">
                  发表评论
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <div v-else class="login-to-comment">
            <p>请 <el-link type="primary" @click="goToLogin">登录</el-link> 后发表评论</p>
          </div>
          
          <div class="comments-list" v-loading="loadingComments">
            <div v-if="comments.length === 0 && !loadingComments" class="no-comments">
              <el-empty description="暂无评论，快来发表第一条评论吧！"></el-empty>
            </div>
            
            <div v-else class="comment-items">
              <div v-for="comment in comments" :key="comment.commentId" class="comment-item">
                <div class="comment-header">
                  <div class="comment-user">
                    <el-avatar :size="40" :src="comment.user?.avatar || defaultAvatarUrl"></el-avatar>
                    <div class="user-info">
                      <h4>{{ comment.user?.nickname || comment.user?.username || '匿名用户' }}</h4>
                      <span class="comment-time">{{ comment.createdAt }}</span>
                    </div>
                  </div>
                  <div class="comment-actions">
                    <el-button 
                      v-if="isCurrentUserComment(comment)" 
                      type="danger" 
                      size="small" 
                      plain
                      @click="deleteComment(comment.commentId)"
                    >
                      删除
                    </el-button>
                    <span class="like-count">
                      <el-button type="text" @click="likeComment(comment)">
                        <el-icon><Star /></el-icon>
                      </el-button>
                      {{ comment.likeCount || 0 }}
                    </span>
                  </div>
                </div>
                
                <div class="comment-content">
                  {{ comment.content }}
                </div>
                
                <div v-if="comment.images && comment.images.length > 0" class="comment-images">
                  <el-image
                    v-for="(image, index) in comment.images"
                    :key="index"
                    :src="image"
                    :preview-src-list="comment.images"
                    fit="cover"
                    class="comment-image"
                  ></el-image>
                </div>
                
                <div v-if="comment.childComments && comment.childComments.length > 0" class="reply-list">
                  <div v-for="reply in comment.childComments" :key="reply.commentId" class="reply-item">
                    <div class="reply-header">
                      <div class="reply-user">
                        <el-avatar :size="30" :src="reply.user?.avatar || defaultAvatarUrl"></el-avatar>
                        <div class="user-info">
                          <h5>{{ reply.user?.nickname || reply.user?.username || '匿名用户' }}</h5>
                          <span class="reply-time">{{ reply.createdAt }}</span>
                        </div>
                      </div>
                      <div class="reply-actions">
                        <el-button 
                          v-if="isCurrentUserComment(reply)" 
                          type="danger" 
                          size="small" 
                          plain
                          @click="deleteComment(reply.commentId)"
                        >
                          删除
                        </el-button>
                      </div>
                    </div>
                    <div class="reply-content">
                      <span class="reply-to" v-if="reply.parentComment">
                        回复 <strong>{{ reply.parentComment.user?.nickname || reply.parentComment.user?.username || '匿名用户' }}</strong>:
                      </span>
                      {{ reply.content }}
                    </div>
                  </div>
                </div>
                
                <div v-if="isLoggedIn && replyingTo === comment.commentId" class="reply-form">
                  <el-input
                    v-model="replyForm.content"
                    type="textarea"
                    :rows="2"
                    placeholder="回复评论..."
                    maxlength="300"
                    show-word-limit
                  ></el-input>
                  <div class="reply-form-actions">
                    <el-button size="small" @click="cancelReply">取消</el-button>
                    <el-button type="primary" size="small" @click="submitReply(comment.commentId)" :loading="submittingReply">
                      回复
                    </el-button>
                  </div>
                </div>
                
                <div v-else-if="isLoggedIn" class="reply-button">
                  <el-button type="text" @click="showReplyForm(comment.commentId)">
                    回复
                  </el-button>
                </div>
              </div>
            </div>
            
            <div class="pagination-container" v-if="comments.length > 0">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </div>
      
      <div v-else-if="!loading" class="empty-state">
        <el-empty description="未找到景点信息">
          <el-button type="primary" @click="goBack">返回列表</el-button>
        </el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Location, Star, Ticket, MapLocation, View, Clock, Phone, Link, Back, ArrowLeft } from '@element-plus/icons-vue';
import { getAttractionById } from '@/api/attraction';
import { useUserStore } from '@/stores/user';
import api from '@/api/auth';

const route = useRoute();
const router = useRouter();
const id = ref(route.params.id);
const loading = ref(true);
const attraction = ref(null);

// 用户状态
const userStore = useUserStore();
const isLoggedIn = computed(() => userStore.isLoggedIn);
const currentUser = computed(() => userStore.user);

// 评论相关
const comments = ref([]);
const loadingComments = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const defaultAvatarUrl = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 评论表单
const commentFormRef = ref(null);
const commentForm = ref({
  content: '',
  attractionId: route.params.id
});
const commentRules = {
  content: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 2, max: 500, message: '评论长度在2到500个字符之间', trigger: 'blur' }
  ]
};
const submittingComment = ref(false);

// 回复相关
const replyingTo = ref(null);
const replyForm = ref({
  content: '',
  attractionId: route.params.id,
  parentCommentId: null
});
const submittingReply = ref(false);

// 获取景点详情
const fetchAttractionDetail = async () => {
  loading.value = true;
  try {
    const response = await getAttractionById(id.value);
    if (response.code === 200 && response.data) {
      attraction.value = response.data;
    } else {
      ElMessage.error(response.message || '获取景点详情失败');
    }
  } catch (error) {
    console.error('获取景点详情失败:', error);
    ElMessage.error('获取景点详情失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 格式化开放时间
const formatOpeningHours = (hours) => {
  if (!hours) return '暂无信息';
  if (Array.isArray(hours)) {
    return hours.join('; ');
  }
  return hours;
};

// 添加到收藏
const addToFavorites = () => {
  // 实现收藏功能
  ElMessage.success('收藏成功');
};

// 在地图上查看
const viewOnMap = () => {
  if (attraction.value && attraction.value.longitude && attraction.value.latitude) {
    // 打开地图选择对话框
    ElMessageBox.confirm(
      '请选择要使用的地图服务',
      '查看地图',
      {
        confirmButtonText: '腾讯地图',
        cancelButtonText: '百度地图',
        distinguishCancelAndClose: true,
        closeOnClickModal: false,
        type: 'info'
      }
    )
      .then(() => {
        // 用户选择腾讯地图
        window.open(`https://map.qq.com/?type=marker&isopeninfowin=1&markertype=1&pointx=${attraction.value.longitude}&pointy=${attraction.value.latitude}&name=${encodeURIComponent(attraction.value.name)}`, '_blank');
      })
      .catch((action) => {
        if (action === 'cancel') {
          // 用户选择百度地图
          window.open(`https://api.map.baidu.com/marker?location=${attraction.value.latitude},${attraction.value.longitude}&title=${encodeURIComponent(attraction.value.name)}&content=${encodeURIComponent(attraction.value.address || '')}&output=html`, '_blank');
        }
      });
  } else {
    ElMessage.warning('暂无地理位置信息');
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 获取评论列表
const fetchComments = async () => {
  loadingComments.value = true;
  try {
    const response = await api.get(`/comment/attraction/${route.params.id}`, {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    });
    
    if (response.code === 200) {
      comments.value = response.data.list || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取评论失败');
    }
  } catch (error) {
    console.error('获取评论失败:', error);
    ElMessage.error('获取评论失败，请稍后再试');
  } finally {
    loadingComments.value = false;
  }
};

// 提交评论
const submitComment = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再发表评论');
    return;
  }
  
  await commentFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submittingComment.value = true;
    try {
      const response = await api.post('/comment/addComment', {
        attractionId: Number(route.params.id),
        content: commentForm.value.content
      });
      
      if (response.code === 200) {
        ElMessage.success('评论发表成功，等待管理员审核后方可展示');
        commentForm.value.content = '';
        // 重新获取评论列表
        fetchComments();
      } else {
        ElMessage.error(response.message || '评论发表失败');
      }
    } catch (error) {
      console.error('发表评论失败:', error);
      ElMessage.error('发表评论失败，请稍后再试');
    } finally {
      submittingComment.value = false;
    }
  });
};

// 显示回复表单
const showReplyForm = (commentId) => {
  replyingTo.value = commentId;
  replyForm.value.parentCommentId = commentId;
  replyForm.value.content = '';
};

// 取消回复
const cancelReply = () => {
  replyingTo.value = null;
  replyForm.value.content = '';
  replyForm.value.parentCommentId = null;
};

// 提交回复
const submitReply = async (commentId) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再回复评论');
    return;
  }
  
  if (!replyForm.value.content.trim()) {
    ElMessage.warning('回复内容不能为空');
    return;
  }
  
  submittingReply.value = true;
  try {
    const response = await api.post('/comment/addComment', {
      attractionId: Number(route.params.id),
      content: replyForm.value.content,
      parentCommentId: commentId
    });
    
    if (response.code === 200) {
      ElMessage.success('回复发表成功，等待管理员审核后方可展示');
      cancelReply();
      // 重新获取评论列表
      fetchComments();
    } else {
      ElMessage.error(response.message || '回复发表失败');
    }
  } catch (error) {
    console.error('发表回复失败:', error);
    ElMessage.error('发表回复失败，请稍后再试');
  } finally {
    submittingReply.value = false;
  }
};

// 删除评论
const deleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条评论吗？此操作不可恢复。',
      '删除评论',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const response = await api.post(`/comment/deleteComment/${commentId}`);
    
    if (response.code === 200) {
      ElMessage.success('评论已删除');
      // 重新获取评论列表
      fetchComments();
    } else {
      ElMessage.error(response.message || '删除评论失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error);
      ElMessage.error('删除评论失败，请稍后再试');
    }
  }
};

// 点赞评论
const likeComment = async (comment) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再点赞');
    return;
  }
  
  try {
    const response = await api.post(`/comment/like/${comment.commentId}`);
    
    if (response.code === 200) {
      // 更新点赞数
      comment.likeCount = (comment.likeCount || 0) + 1;
      ElMessage.success('点赞成功');
    } else {
      ElMessage.error(response.message || '点赞失败');
    }
  } catch (error) {
    console.error('点赞失败:', error);
    ElMessage.error('点赞失败，请稍后再试');
  }
};

// 判断是否是当前用户的评论
const isCurrentUserComment = (comment) => {
  return isLoggedIn.value && currentUser.value && comment.user && 
         currentUser.value.userId === comment.user.userId;
};

// 前往登录页
const goToLogin = () => {
  router.push({
    name: 'Login',
    query: { redirect: route.fullPath }
  });
};

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchComments();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchComments();
};

// 返回首页
const goHome = () => {
  router.push('/');
};

onMounted(() => {
  fetchAttractionDetail();
  fetchComments();
});
</script>

<style scoped>
.attraction-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.attraction-card {
  margin-bottom: 20px;
}

.attraction-header {
  margin-bottom: 20px;
}

.attraction-header h1 {
  margin: 0 0 10px;
  font-size: 28px;
  color: #303133;
}

.attraction-meta-top {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.rating {
  display: flex;
  align-items: center;
  gap: 5px;
}

.view-count {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
}

.attraction-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 30px;
}

.attraction-gallery {
  width: 100%;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.attraction-image {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  border-radius: 4px;
}

.attraction-description h2 {
  margin: 0 0 15px;
  font-size: 20px;
  color: #303133;
}

.attraction-description p {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 20px;
}

.attraction-meta {
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  color: #606266;
}

.meta-item .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.attraction-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.tag-item {
  margin-right: 0;
}

.attraction-actions {
  display: flex;
  gap: 10px;
}

.attraction-detail-section,
.attraction-traffic-section,
.attraction-gallery-section {
  margin-bottom: 30px;
}

.attraction-detail-section h2,
.attraction-traffic-section h2,
.attraction-gallery-section h2 {
  margin: 0 0 15px;
  font-size: 20px;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.detail-content,
.traffic-content {
  color: #606266;
  line-height: 1.8;
  white-space: pre-line;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.gallery-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
}

.gallery-image {
  width: 100%;
  height: 150px;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
}

/**.gallery-image:hover {
  transform: scale(1.03);
}**/

.empty-state {
  padding: 40px 0;
  display: flex;
  justify-content: center;
}

@media (min-width: 768px) {
  .attraction-content {
    flex-direction: row;
  }
  
  .attraction-gallery {
    width: 60%;
  }
  
  .attraction-info {
    width: 40%;
    padding-left: 20px;
  }
}

/* 评论区样式 */
.attraction-comments-section {
  margin-top: 40px;
  margin-bottom: 40px;
}

.attraction-comments-section h2 {
  margin: 0 0 20px;
  font-size: 20px;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.comment-form-container {
  margin-bottom: 30px;
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
}

.login-to-comment {
  margin-bottom: 30px;
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  text-align: center;
  color: #909399;
}

.comments-list {
  margin-top: 20px;
}

.no-comments {
  padding: 30px 0;
}

.comment-item {
  margin-bottom: 25px;
  padding-bottom: 25px;
  border-bottom: 1px solid #ebeef5;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.comment-user {
  display: flex;
  align-items: center;
}

.user-info {
  margin-left: 10px;
}

.user-info h4, .user-info h5 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.user-info h5 {
  font-size: 14px;
}

.comment-time, .reply-time {
  font-size: 12px;
  color: #909399;
}

.comment-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.like-count {
  display: flex;
  align-items: center;
  color: #F56C6C;
}

.comment-content {
  margin: 10px 0;
  color: #303133;
  line-height: 1.6;
  white-space: pre-wrap;
}

.comment-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.comment-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
}

.reply-list {
  margin-top: 15px;
  margin-left: 50px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.reply-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.reply-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 5px;
}

.reply-user {
  display: flex;
  align-items: center;
}

.reply-content {
  margin: 5px 0;
  color: #303133;
  line-height: 1.6;
}

.reply-to {
  color: #909399;
  margin-right: 5px;
}

.reply-form {
  margin-top: 15px;
  margin-left: 50px;
}

.reply-form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  gap: 10px;
}

.reply-button {
  margin-top: 10px;
  margin-left: 50px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.navigation-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 添加导航按钮样式 */
.navigation-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

@media (max-width: 768px) {
  .navigation-buttons {
    flex-direction: column;
    gap: 8px;
  }
}
</style> 